 <!--
 * @Author: zeng_ze
 * @Date: 2019-11-7
 * @Description: 系统管理下的用户管理
 -->
<template>
  <div class="main-wrapper user-container">
    <fks-query-page
      ref="userTable"
      v-loading="listLoading"
      :data="tableData"
      :total="total"
      :page-size.sync="pageSize"
      :current-page.sync="currentPage"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 50, 100]"
      :element-loading-text="LANG.LOADING"
      :table-name="LANG.USER_LIST"
      @query="getAllUsers"
      @selection-change="changeChecked"
      @sort-change="sortHandler"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-input
            v-model="userName"
            size
            :placeholder="LANG.USER_SEARCH_PLACEHOLDER"
            class="single-searchBox-item"
            clearable
            maxlength="50"
            @clear="serch"
            @keyup.enter.native="serch"
          >
            <fks-button
              slot="append"
              icon="fks-icon-search"
              @click="serch"
            />
          </fks-input>
          <!-- 用户导入 -->
          <fks-button
            v-permission="['user:import']"
            v-saas:user="['main', 'notSaas']"
            @click="openImportDialog"
          >
            <i class="fks-icon-import" />

            <span style="margin-left: 8px; vertical-align: middle">
              {{ LANG.IMPORT }}
            </span>
          </fks-button>
          <!-- 导出用户 -->
          <fks-button
            v-permission="['user:export']"
            @click="exportUser"
          >
            <i class="fks-icon-export" />
            <span style="margin-left: 8px">{{ LANG.EXPORT }}</span>
          </fks-button>
          <fks-button
            v-permission="['user:add']"
            v-saas:user="['main', 'notSaas']"
            icon="fks-icon-plus"
            type="primary"
            @click="add"
          >
            <span style="vertical-align: middle">{{ LANG.ADD }}</span>
          </fks-button>
        </div>
      </template>
      <template>
        <fks-table-column
          type="selection"
          width="55"
        />
        <fks-table-column
          type="index"
          align="center"
          label="#"
        >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </fks-table-column>
        <!-- 姓名 -->
        <fks-table-column
          prop="userFullname"
          :label="LANG.USER_FULL_NAME"
          is-link
          sortable="custom"
          min-width="100px"
          @link="gotoView"
        />
        <!-- 用户名 -->
        <fks-table-column
          prop="userName"
          :label="LANG.USERNAME"
          min-width="90px"
        />
        <fks-table-column
          prop="sex"
          :label="LANG.SEX"
          sortable="custom"
          width="120"
        />
        <!-- 邮箱 -->
        <fks-table-column
          prop="email"
          :label="LANG.EMAIL"
          min-width="150"
        />
        <!-- 联系方式 -->
        <fks-table-column
          prop="phone"
          :label="LANG.PHONE"
          min-width="130"
        />
        <fks-table-column
          prop="accountStatus"
          :label="LANG.ACCOUNT_STATUS"
        >
          <div slot-scope="scope">
            <fks-tag
              v-if="scope.row.accountStatus == 1"
              type="success"
            >
              {{ LANG.ACTIVATE }}
            </fks-tag>
            <fks-tag
              v-if="scope.row.accountStatus == 2"
              type="warning"
            >
              {{ LANG.DORMANT }}
            </fks-tag>
            <fks-tag
              v-if="scope.row.accountStatus == 3"
              type="danger"
            >
              {{ LANG.LOGOUT }}
            </fks-tag>
          </div>
        </fks-table-column>
        <fks-table-column
          v-if="saasPermission(['main', 'notSaas'], 'user')"
          :label="LANG.OPERATION"
          width="150"
          align="left"
        >
          <template slot-scope="scope">
            <fks-button
              v-permission="['user:edit']"
              type="text"
              @click.stop="editClick(scope.row)"
            >
              {{ LANG.EDIT }}
            </fks-button>
            <fks-button
              v-if="scope.row.accountStatus != 2"
              type="text"
              @click.stop="lock(scope.row)"
            >
              {{ LANG.DORMANT }}
            </fks-button>
            <fks-button
              v-if="scope.row.accountStatus != 1"
              type="text"
              @click.stop="active(scope.row)"
            >
              {{ LANG.ACTIVATE }}
            </fks-button>
            <fks-button
              v-if="
                scope.row.accountStatus == 1 || scope.row.accountStatus == 2
              "
              type="text"
              danger-text
              @click.stop="logOff(scope.row)"
            >
              {{ LANG.LOGOUT }}
            </fks-button>
          </template>
        </fks-table-column>
      </template>
    </fks-query-page>
    <user-info
      v-if="userVisible"
      :user-type="userTitle"
      :data="userData"
      :visible.sync="userVisible"
    />
    <import-user
      :visible.sync="importVisible"
      :flag="importFlag"
      @fetchData="getAllUsers"
    />
  </div>
</template>
<script>
import { exportFile } from '@/utils/file'
import * as types from '@/store/Getter/getterTypes.js'
import Mix from '@/mixins/module'
import * as System from './api'
import UserInfo from './UserInfo'
import importUser from './Import'
export default {
  name: 'User',
  components: { UserInfo, importUser },
  mixins: [Mix],
  data() {
    return {
      importFlag: 'user',
      userName: '',
      importVisible: false,
      listLoading: false,
      userId: '',
      //用户角色 列表 加载动画
      roleLoading: true,
      //用户角色 列表 数组
      roleData: [],
      //用户角色 分页数据
      //用户角色弹窗 显隐
      roleVisible: false,
      tableData: [],
      //新增用户、编辑用户弹窗 显隐
      userVisible: false,
      userTitle: '',
      userData: {},
      //导入用户弹出 显隐
      exportVisible: false,
      //导入用户弹窗标题
      exportName: '导入用户',
      //新增用户、编辑用户弹窗 标题
      fileList: [],
      ACESS_TOKEN: this.$storage.get('access_token'),
      //上传的地址
      uploadUrl: '',
      title: '',
      rowData: null, //编辑时，克隆原始数据
      diffData: null, //差异数据，编辑修改保存时，只上传修改过的数据
      pageSize: 20,
      total: 0,
      currentPage: 1,
      excelExportLikeParam: {},
      account: {},
      checkedId: [],
      row: {},
      searchValue: {
        searchValue: ''
      },
      formData: {
        attachment: '',
        files: 0
      },
      sort: '',
      columnName: '',
      Form: {
        name: '',
        sex: '',
        userName: '',
        password: '',
        email: '',
        phone: '',
        orgNo: '',
        orgName: '',
        accountStatus: 1,
        //新增时 默认长期
        accountPeriod: 1
      }
    }
  },
  computed: {
    theme() {
      return this.$store.getters[types.THEME]
    },
    type() {
      return this.$store.state.portal.type
    },
    portalId() {
      return this.$store.state.portal.id
    }
  },
  created() {
    this.getAllUsers()
  },
  methods: {
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop == 'userFullname' ? 'user_fullname' : 'sex'
      }
      params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName,
        searchValue: this.userName,
        needOrg: false
      }
      this.getUserList(params)
    },
    active(row) {
      System.editUsers(
        JSON.stringify(
          Object.assign({
            userName: row.userName,
            id: row.id,
            accountStatus: 1
          })
        )
      )
        .then((response) => {
          if (response.status) {
            this.$message.success(this.LANG.ACTIVATE_SUCCESS)
            this.getAllUsers()
          }
        })
        .catch(() => {})
    },
    lock(row) {
      System.editUsers(
        JSON.stringify(
          Object.assign({
            userName: row.userName,
            id: row.id,
            accountStatus: 2
          })
        )
      )
        .then((response) => {
          if (response.status) {
            this.$message.success(this.LANG.DORMANT_SUCCESS)
            this.getAllUsers()
          } else {
            this.$message.error(this.LANG.DORMANT_FALIED)
          }
        })
        .catch(() => {})
    },
    logOff(row) {
      this.$confirm(this.LANG.CANCEL_TIP, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.LOGOUT,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          System.editUsers(
            JSON.stringify({
              userName: row.userName,
              id: row.id,
              accountStatus: 3
            })
          )
            .then((response) => {
              if (response.status) {
                this.$message.success(this.LANG.LOGOFF_SUCCESS)
                this.getAllUsers()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    // 查看用户
    gotoView({ row }) {
      this.userVisible = true
      this.userTitle = 'view'
      this.userData = JSON.parse(JSON.stringify(row))
    },
    //点击后修改选中状态
    changeSelected(row) {
      let w = true
      this.checkedId.forEach((item) => {
        if (item == row.id) {
          w = false
        }
      })
      return w
    },
    // 选择用户时触发
    changeChecked(val) {
      this.checkedId = []
      val.forEach((item) => {
        this.checkedId.push(item.id)
      })
    },
    //导出用户
    exportUser() {
      if (this.checkedId.length > 0 || this.userName) {
        this.userName
          ? (this.excelExportLikeParam.searchValue = this.userName)
          : (this.excelExportLikeParam.idList = this.checkedId)
      } else {
        this.excelExportLikeParam.exportAll = true
      }
      System.exportUser(this.excelExportLikeParam)
        .then((res) => {
          if (res.request.response.type == 'application/json') {
            let fileReader = new FileReader()
            fileReader.readAsText(res.data)
            let that = this
            fileReader.onload = function (result) {
              let jsondata = JSON.parse(result.target.result)
              if (jsondata.status) {
                that.$message.success(that.LANG.EXPORT_SUCCESS)
              } else {
                that.$message.error(that.LANG.EXPORT_FAILED)
              }
            }
          } else {
            // 'application/vnd.ms-excel'
            exportFile(res)
            this.$message.success(this.LANG.EXPORT_SUCCESS)
          }
        })
        .catch(() => {})
    },
    //打开导入用户的弹窗
    openImportDialog() {
      this.importVisible = true
    },
    //新增用户 弹窗
    add() {
      this.userVisible = true
      this.userTitle = 'add'
    },
    //编辑用户 弹窗
    editClick(row) {
      this.userVisible = true
      this.userTitle = 'edit'
      this.userData = JSON.parse(JSON.stringify(row))
    },
    serch() {
      this.currentPage = 1
      this.getAllUsers()
    },
    //获取所有用户分页
    getAllUsers() {
      let param = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        searchValue: this.userName,
        sort: this.sort,
        columnName: this.columnName,
        needOrg: false
      }
      this.getUserList(param)
    },
    @permission('user:query')
    getUserList(param) {
      this.listLoading = true
      System.getUsers(param)
        .then((res) => {
          if (res.status) {
            this.tableData = res.data.list
            this.total = res.data.total
          }
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
          this.tableData = []
          this.total = 0
        })
    },
    //关闭导入用户弹窗
    cancelExoport() {
      this.exportVisible = false
      this.fileList = []
    },
    //提交导入用户
    submit() {
      this.$refs.upload.submit()
      this.getAllUsers()
      this.cancelExoport()
    }
  }
}
</script>
 <style lang="scss" scoped>
.role {
  height: 400px;
}
// .single-searchBox-item {
//   width: 30%;
//   max-width: 300px;
// }
.user-container {
  min-width: 668px;
}
::v-deep .role-list {
  padding-top: 0 !important;
  margin-top: 0 !important;
}
.more {
  width: 28px;
  margin-left: 5px;
}
.fks-icon-more {
  width: 28px;
}
.password {
  font-size: 12px;
}
.word {
  color: #409eff;
}
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>